
import {ChangeDetectorRef, Component} from "@angular/core";
import {NavController, NavParams, AlertController, ToastController, ActionSheetController} from "ionic-angular";
import {HttpService} from "../../../providers/http.service";
import {CommonFunc} from "../../../providers/commonFunc";
import {HomePage} from "../../home/home";
import { Storage } from "@ionic/storage";
import {Camera, CameraOptions} from "@ionic-native/camera";
import {FileTransfer, FileTransferObject, FileUploadOptions} from "@ionic-native/file-transfer";
import {appConfig} from "../../../providers/config";
import {PhotoViewer} from "@ionic-native/photo-viewer";
/**
 * 多台电梯检查列表
 */
@Component({
  templateUrl: "check-elevator-list.html"
})
export class CheckElevatorList {
    public type = null;
    public checkNameUrl: any = null;
    public checkerId: any = null;
    public checkerName: any = null;

    // 检查项集合
    public checklist:any=[];
    // 计划Id
    public planId:any;

    public levels:any=[];
    public objData:any=[];

    public protectdatas:any;

    public temp:any;

    public implementObject:any;
    public headMan:any;
    public checkMan:any;
    public userId:any;
    public objId:any;
    public flag:any="show";

    private appConfig: any;

    public signPhoto:any;

    constructor(
        private navParams: NavParams,
        private commonFunc: CommonFunc,
        private httpService: HttpService,
        private storage: Storage,
        private navCtrl: NavController,
        public alertCtrl: AlertController,
        private camera: Camera,
        private transfer: FileTransfer,
        private ActionSheet: ActionSheetController,
        private photoViewer: PhotoViewer,
        public cd: ChangeDetectorRef,
        private toast: ToastController

    ) {

        this.appConfig = appConfig;

        this.storage.get("user").then(data => {
            this.checkerId = data.id;
            this.checkerName = data.userName;
        });

        this.storage.get("objData").then(data => {
            this.implementObject = data.implementObject;
            this.headMan  =data.headMan;
            this.checkMan = data.checkMan;
            this.userId = data.userId;
            this.objId = data.objId;
        });

    }
    ionViewWillEnter() {
        this.levels = this.navParams.get("checklist");

        console.log(this.levels);

    }

    accordion(index,temp) {
        this.temp=temp+index;
    }


    // 提交检查项
    submit() {
        console.log(this.levels);

        console.log(this.implementObject);

        if (this.levels == null || this.levels.length == 0 || this.levels==undefined) {
            let tt = this.toast.create({
                message: "请先扫描电梯进行检查！",
                duration: 2000,
                position: "top"
            });
            tt.present();
            return;
        }

        if(this.signPhoto ==undefined || this.signPhoto == null){
            let tt = this.toast.create({
                message: "请签上您的真实姓名!",
                duration: 3000,
                position: "top"
            });
            tt.present();
            return false;
        }

        this.httpService.addCheckItemApp({"list": this.levels,"implementObject":this.implementObject,
            "headMan":this.headMan,"checkMan":this.checkMan,"userId":this.userId,"objId":this.objId,"signPhoto":this.signPhoto}).subscribe(data => {
            if (data.status != 200) {
                window["jQuery"]("#signatureid").remove();
                window["jQuery"]("#showImage").remove();
                let toast = this.commonFunc.showInsideErrorToast(data);
                toast.present();
                return;
            }else{
                window["jQuery"]("#signatureid").remove();
                window["jQuery"]("#showImage").remove();
                let tt = this.toast.create({
                    message: "提交成功",
                    duration: 3000,
                    position: "top"
                });
                tt.present();

                this.levels = [];

                /*this.navCtrl.push(HomePage);*/
                this.navCtrl.setRoot(HomePage);

                return;
            }
        });
        console.log(this.levels);
    }

    // 删除功能
    removeItem(data) {
        // 创建一个集合
        let idlist: any = [];
        // 创建一个返回的集合
        let returnlist: any = [];

        idlist.push(data.id);

        for (let i = 0; i < this.levels.length; i++) {
            if (idlist.indexOf(this.levels[i].id) == -1) {
                returnlist.push(this.levels[i]);
            }
        }
        this.levels = returnlist;

        console.log(returnlist)
        console.log(this.levels)
    }


    doCamera(index, i) {
        let options: CameraOptions = {
            quality: 85, // destinationType: this.camera.DestinationType.DATA_URL,
            // encodingType: this.camera.EncodingType.JPEG,
            mediaType: this.camera.MediaType.PICTURE,
            targetWidth: 1500,
            targetHeight: 1500,
            correctOrientation: true
        };
        this.camera.getPicture(options).then(imageData => {
            //判断网络状态
            console.log("判断网络状态");
            if (!this.commonFunc.hasNetWork()) {
                if (i == 'c') {
                    console.log("c")
                    this.levels[index].result.picUrl.push(imageData);
                } else {
                    console.log(" ! c")
                    this.levels[index].result.picUrl[i] = imageData;
                }
                return;
            }
            const options: FileUploadOptions = {};
            let serverUrl = encodeURI(appConfig.IP_URL + appConfig.API.upload);
            //let serverUrl =  encodeURI('http://192.168.43.242:8080/upload/base.ctrl');
            options.fileKey = 'file';
            options.fileName = 'test.jpg';
            options.mimeType = 'image/jpeg';
            const fileTransfer: FileTransferObject = this.transfer.create();
            fileTransfer.upload(imageData, serverUrl, options).then(restul => {
                let aa = JSON.parse(restul['response']);
                console.log("输出aa");
                console.log(aa);
                if (aa['status'] == 200) {
                    if (aa['data'].length > 0) {
                        if (i == 'c') {
                            console.log("c")
                            console.log(aa['data']);
                            this.levels[index].result.picUrl.push(aa['data']);

                        } else {
                            console.log("!c")
                            this.levels[index].result.picUrl[i] = aa['data'];
                        }
                    }
                }
                this.cd.detectChanges();
            });
        });
        console.log("1111111111111");
        console.log(this.levels);
        console.log("1111111111111");
    }

    onHold(index, param) {
        let actionSheet = this.ActionSheet.create({
            buttons: [
                {
                    text: '重拍',
                    role: '重拍',
                    handler: () => {
                        let i = this.levels[index].result.picUrl.indexOf(param);
                        this.doCamera(index, i);
                    }
                },
                {
                    text: '查看大图',
                    role: '查看大图',
                    handler: () => {
                        this.photoViewer.show(
                            encodeURI(this.whaturl(param)).replace('%5C', '/'),
                            null,
                            {
                                share: false
                            }
                        );
                    }
                },
                {
                    text: '删除',
                    handler: () => {
                        let i = this.levels[index].result.picUrl.indexOf(param);
                        this.levels[index].result.picUrl.splice(i, 1);
                    }
                },
                {
                    text: '取消',
                    role: '取消',
                    handler: () => {
                        //console.log('Cancel clicked');
                    }
                }
            ]
        });
        actionSheet.present();
    }

    whaturl(url) {
        if ((url + '').indexOf('file') < 0) {
            return this.appConfig.IP_URL + this.appConfig.API.getUpload + url;
        } else {
            return url;
        }
    }

    getImgUrl(param) {
        this.signPhoto = param.imageDate;
        console.log(this.signPhoto);
    }
}
